#include <reg52.h>
#include "UART.h"
#include "Digital_tube.h"
#include "Delay.h"

#define LED P1
unsigned char ans,flag,num=-1;

void LED_change(){
	flag = LED & (0x01<<num);		//将第num位的状态取出来
		if(flag) {
			LED &= ~(0x01<<num);	//点亮某位灯
			UART_SendByte_str("已经将第 ");
			UART_SendByte(num+48);
			UART_SendByte_str(" 位灯点亮...\n");
		}else {
			LED |= (0x01<<num);	//熄灭某位灯
			UART_SendByte_str("已经将第 ");
			UART_SendByte(num+48);
			UART_SendByte_str(" 位灯熄灭...\n");
		}
}

/**
  * @brief  串口中断函数模板
  * @param  无
  * @retval 无
  */
void UART_Routine() interrupt 4
{
	if(RI==1){  //接受中断请求标志位 串口接收中断
		ans=SBUF;
		UART_SendByte(ans);	//将接收到的信息返回发送给计算机

		if(48<=ans && ans<=(48+7)){		//字符0的编码0x30 == 48
			num=ans-48;
			UART_SendByte_str("     输入合法！\n");
			LED_change();
		}else{
			UART_SendByte_str("     输入不合法！ 请输入0-7:");
		}

		RI=0;			//必须软件复位，以便再次接受
	}if(RI==0){

	}
}

void UART_conrol_LED(){
	UART_Init();
	LED = 0xff;
	UART_SendByte_str("这是张庭华的程序! \n");
	UART_SendByte_str("请发送要控制的LED的编号: \n");
	while(1){
		show_LED_bumber(num);
	}
}

void main(){
	UART_conrol_LED();
}



/*----------------------------------------------------------------------------*/
#include <regx52.h>
#include "HC_SR04.h"
#include "Delay.h"
#include "oled.h"
#include "Timer0.h"



unsigned char flag = 0;


void Timer_0_hander() interrupt 1 {
    static unsigned int count = 0;

    // 重载定时器初值
    TL0 = 0x66;
    TH0 = 0xFC;

    // 清除TF0标志位
    TF0 = 0;

    // 增加计数器
    if (++count == 1000) {
        count = 0;

    }
}



// 外部中断处理函数 P32
void External_Interrupt_1(void) interrupt 0 {
    flag = 1;
}



/**
  * @brief  呼吸灯效果
  * @param  duty:占空比 0~100
  * @retval 无
  */
void Breathing_LED(unsigned char duty)
{
    unsigned int i;
    for(i=0;i<800;i++) //延缓亮度变化
    {
        P1= 0x00;
        delay(duty);
        P1= 0xFF;
        delay(100-duty);
    }
}




int main()
{
    unsigned int int_cm,decimal_cm;

	OLED_Init();
	HC_SR04_Init();
    Timer0_Init();
    External_Interrupt0_Init();

	while(1){
        
        if(flag)
        {
            P3_7 = 1;
            OLED_ShowString(2,1,"WAR:Someone");
            OLED_ShowString(1,1,"dis:");
            int_cm = (unsigned int)(HC_SR04_Value * 1.7f/100.0f);
            decimal_cm = (unsigned int)(HC_SR04_Value * 170 % 100);
            OLED_ShowNum(1,8,int_cm,3);
            OLED_ShowChar(1,11,'.');
            OLED_ShowNum(1,12,decimal_cm, 2);
            OLED_ShowString(1,14,"cm");

            Breathing_LED(int_cm/5);
            if(int_cm > 300) 
            {
                flag=0;
            }

        }else{
            OLED_ShowString(1,1,"               ");
            OLED_ShowString(2,1,"               ");
            P3_7 = 0;
            
        }


	}
}